import express from 'express';
import { createConnectionPool } from '../../mysql/index.js';
import axiosInstance from '../../utils/request.js';

const router = express.Router();

// 创建数据库连接池
let connection = await createConnectionPool();
router.post('/verif_api/user/api/recycle_data', async (req, res) => {
    try {
        console.log(`查看`, req.body.user_id);
        if (!req.body.user_id) return res.status(400).send({ error: 'user_id 不存在' });
        const response = await axiosInstance.post('/api_proxy/user/api/recycle_data', { data: { page: 1, so: "" } });
        console.log('Response received:', response.data);

        const data = response.data.data;
        // if (data.length === 0) {
        //     return res.status(204).send();
        // }
        const checkQuery = 'SELECT COUNT(*) AS count FROM verificationmanage WHERE r_id = ? AND username = ?';
        const insertQuery = `
    INSERT INTO verificationmanage (
        r_id, u_id, money, status, fl, username, bz, index_group, loginfailure,
        tokentime, google_key, del_auth, del_time, weight, upload_key, edit_auth,
        today_amt, yes_amt, before_yes
    ) VALUES (
        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
    )
`;

        const insertOrUpdateData = async (item) => {
            try {
                const [rows] = await connection.execute(checkQuery, [item.r_id, item.username]);
                if (rows[0].count > 0) {
                    // Username already exists, do not insert or update
                    console.log(`Username ${item.username} already exists, skipping insert/update.`);
                    return;
                } else {
                    await connection.execute(insertQuery, [
                        item.r_id, req.body.user_id, item.money, item.status, item.fl, item.username, item.bz,
                        item.index_group, item.loginfailure, item.tokentime, item.google_key, item.del_auth,
                        item.del_time, item.weight, item.upload_key, item.edit_auth, item.today_amt,
                        item.yes_amt, item.before_yes
                    ]);
                }
            } catch (error) {
                console.error('Error occurred while inserting/updating data:', error);
            }
        };

        const insertPromises = data.map(item => insertOrUpdateData(item));
        await Promise.all(insertPromises);
        const query = 'SELECT * FROM verificationmanage WHERE u_id = ?';
        const user_id = req.body.user_id;
        const [rows] = await connection.execute(query, [user_id]);
        console.log("index", rows);
        /*   if (!rows.length) {
              rows = [];
          } */
        res.status(200).send({ success: '获取成功', data: rows });
    } catch (error) {
        console.error('Error occurred:', error);
        res.status(500).send({ error: 'Internal Server Error' });
    }
});

router.get('/verif_api/user/api/del_recycle', async (req, res) => {
    const { id } = req.query;
    console.log("查看信息", req.query);
    if (!id) {
        return res.status(400).send({ error: 'id 不存在' });
    }

    try {
        // 删除数据库中匹配的 id 的记录
        const [result] = await connection.execute('DELETE FROM verificationmanage WHERE r_id = ?', [id]);

        if (result.affectedRows === 0) {
            return res.status(404).send({ error: '未找到要删除的记录' });
        }

        // 发送成功响应
        res.status(200).send({ success: 'Order classification deleted successfully' });
    } catch (error) {
        // 记录错误并发送错误响应
        console.error('Error executing query:', error);
        res.status(500).send({ error: 'An error occurred while deleting the order classification' });
    }
})


export default router;

